<?php
	//ActiveRecord.php
class ActiveRecord
{
	protected $tableName; //Name of table in database
	protected $id; //Id of actual record
	protected $fields = array();

	public function __construct()
	{
		$this->tableName = strToLower(get_class($this)).'s'; //Set name of table
	}
	
	public function __set($key,$value)
	{
		$this->fields[$key] = $value;
	}
	
	//Save fields (update or insert)
	public function save()
	{
		if(isset($this->fields))
		{
			if(isset($this->id))
			{
				$result = DB::connect()->createCommand()
									   ->update($this->tableName)
									   ->set($this->fields)
									   ->where(array('id',$this->id))
									   ->query();
				if($result)
				{
					return $result;
				}
				else
				{
					return false;
				}
			}
			else
			{
				$result = DB::connect()->createCommand()
									   ->insert($this->tableName)
							           ->field(implode(',',array_keys($this->fields)))
							           ->values(implode(',',array_values($this->fields)))
							           ->query();
				if($result)
				{
					return $result;
				}
				else
				{
					return false;
				}
			}
		}
		else
		{
			throw new Exception('No information for save() function.');
		}
	}
	
	//Get id for active record methods
	public function get($id)
	{
		$result =  DB::connect()->createCommand()
							->select('id')
							->from($this->tableName)
							->where(array('id',$id))
							->getRow();
		if($result)
		{
			$this->id = $id;
			$this->fields = array();
			return true;
		}	
		else
		{
			return false;
		}	
	}

	//Get fields 
	public function getFields($fields)
	{
		if(isset($this->id))
		{
			$result = DB::connect()->createCommand()
							   ->select($fields)
							   ->from($this->tableName)
							   ->where(array('id',$this->id))
							   ->getAll();
			if(!empty($result))
			{
				return $result;
			}	
			else
			{
				return false;
			}				   
		}
	}
	
	//Delete record
	public function delete()
	{
		if(!empty($this->id))
		{
			$result = DB::connect()->createCommand()
								   ->delete($this->tableName)
								   ->where(array('id',$this->id))
								   ->query();
			if($result)
			{
				return $result;
			}
			else
			{
				return false;
			}
		}
		else
		{
			throw new Exception('No information for delete() function.');
		}
	}

	//Get all rows fields from table
	public function getAllFields($fields)
	{
		$result = DB::connect()->createCommand()
							   ->select($fields)
							   ->from($this->tableName)
							   ->getAll();
		if(!empty($result))
		{
			return $result;
		}	
		else
		{
			return false;
		}
	}
}	